// Fill out your copyright notice in the Description page of Project Settings.


#include "UserWidget/WidgetComponent/GlobalNotificationWidget.h"
#include "Components/Border.h"
#include "Components/TextBlock.h"
#include "Libraries/CommonLibrary.h"

void UGlobalNotificationWidget::NativeOnInitialized() {
	Super::NativeOnInitialized();
	DisplayTime = 4.f;
}

void UGlobalNotificationWidget::DisplayGlobalNotification(float InDisplayTime, FText InHeadline,
	FText InTopText, bool InSpecialArea, FText InSpecialAreaText,
	bool InGiveXP, int32 InXPValue, FLinearColor InSpecialAreaColor,
	FLinearColor InHeadlineColor, FLinearColor InXPTextColor)
{
	if (GetWorld()->GetTimerManager().IsTimerActive(FirstHandle) || GetWorld()->GetTimerManager().IsTimerActive(SecondHandle)) return;
	DisplayTime = InDisplayTime;
	Headline->SetText(InHeadline);
	TopText->SetText(InTopText);
	XPText->SetVisibility(InSpecialArea ? ESlateVisibility::SelfHitTestInvisible : ESlateVisibility::Collapsed);
	SpecialText->SetText(InSpecialAreaText);
	CenterBorder->SetVisibility(InGiveXP ? ESlateVisibility::SelfHitTestInvisible : ESlateVisibility::Collapsed);
	XPText->SetText(FText::FromString(FString::Printf(TEXT("+%iXP"), InXPValue)));
	CenterBorder->SetBrushColor(InSpecialAreaColor);
	Headline->SetColorAndOpacity(FSlateColor(InHeadlineColor));
	XPText->SetColorAndOpacity(FSlateColor(InXPTextColor));
	UWidgetAnimation* DisplayAnim = UCommonLibrary::GetAnimInstance(GetClass(), FText::FromString("DisplayAnim"));
	PlayAnimation(DisplayAnim);
	FTimerDelegate RespawnDelegate = FTimerDelegate::CreateUObject(this, &UGlobalNotificationWidget::FirstDelayLater);
	GetWorld()->GetTimerManager().SetTimer(FirstHandle, RespawnDelegate, DisplayAnim->GetEndTime() + DisplayTime, false);
}

void UGlobalNotificationWidget::FirstDelayLater() {
	UWidgetAnimation* DisplayAnim = UCommonLibrary::GetAnimInstance(GetClass(), FText::FromString("DisplayAnim"));
	PlayAnimation(DisplayAnim, 0.f, 1.f, EUMGSequencePlayMode::Reverse);
	FTimerDelegate RespawnDelegate = FTimerDelegate::CreateUObject(this, &UGlobalNotificationWidget::SecondDelayLater);
	GetWorld()->GetTimerManager().SetTimer(SecondHandle, RespawnDelegate, DisplayAnim->GetEndTime() + 0.25f, false);
	GetWorld()->GetTimerManager().ClearTimer(FirstHandle);
}

void UGlobalNotificationWidget::SecondDelayLater() {
	RemoveFromParent();
	GetWorld()->GetTimerManager().ClearTimer(SecondHandle);
}

FSlateFontInfo UGlobalNotificationWidget::MakeOutlineColor(FSlateFontInfo SlateFontInfo, FLinearColor OutlineColor) {
	FSlateFontInfo Result = SlateFontInfo;
	Result.OutlineSettings.OutlineColor = FLinearColor(OutlineColor - FLinearColor(0.2f, 0.2f, 0.2f, 0.5f));
	return Result;
}
